<template>
  <div class="page-container">
    <a-card :bordered="false" size="small" style="margin-bottom: 10px">
      <a-row :gutter="16">
        <a-col class="search-row" :span="20">
          <a-form layout="inline">
            <a-form-item label="名称">
              <a-input
                size="small"
                v-model:value="queryParams.departmentName"
                placeholder="请输入"
                allow-clear
              >
              </a-input>
            </a-form-item>
            <a-form-item label="状态">
              <a-select
                size="small"
                v-model:value="queryParams.status"
                placeholder="请选择"
                @change="handleSearch"
              >
                <a-select-option value="正常">正常</a-select-option>
                <a-select-option value="禁用">禁用</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" size="small" @click="handleSearch">查询</a-button>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col class="search-row right-btn-container" :span="4">
          <!--<a-button type="primary" size="small" @click="handleCreateRows" style="margin-right: 10px"-->
          <!--  >批量新增</a-button-->
          <!--&gt;-->
          <a-button type="primary" size="small" @click="handleCreate">新增</a-button>
        </a-col>
      </a-row>
    </a-card>

    <a-table :dataSource="dataSource" :columns="columns" :pagination="false" size="small">
      <template #bodyCell="{ record, column }">
        <template v-if="column.dataIndex === 'status'">
          <a-tag
            v-if="record.status === '正常'"
            style="cursor: pointer"
            color="green"
            @click="handleChangeStatus(record)"
            >{{ record.status }}</a-tag
          >
          <a-tag
            v-if="record.status === '禁用'"
            style="cursor: pointer"
            color="orange"
            @click="handleChangeStatus(record)"
            >{{ record.status }}</a-tag
          >
        </template>
        <template v-if="column.dataIndex === 'operation'">
          <a
            style="margin-right: 10px"
            v-if="record.departmentName !== '管理员组' && record.departmentName !== '总公司'"
            @click="handleEdit(record)"
            >修改</a
          >
        </template>
      </template>
    </a-table>

    <!--<a-pagination-->
    <!--  v-model:current="queryParams.page"-->
    <!--  v-model:page-size="queryParams.limit"-->
    <!--  style="margin-top: 20px"-->
    <!--  hideOnSinglePage-->
    <!--  showSizeChanger-->
    <!--  :total="total"-->
    <!--  show-less-items-->
    <!--  size="small"-->
    <!--  @change="getList"-->
    <!--/>-->

    <a-modal v-model:open="visible" :title="title" width="400px" destroy-on-close @ok="handleOk">
      <a-form
        ref="formRef"
        :model="form"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        autocomplete="off"
      >
        <a-form-item label="名称" name="name" :rules="[{ required: true, message: '请输入名称!' }]">
          <a-input v-model:value="form.name" size="small" />
        </a-form-item>
        <a-form-item
          label="简称"
          name="simName"
          :rules="[{ required: true, validator: checkCompanyAbbreviation }]"
        >
          <a-input v-model:value="form.simName" size="small" />
        </a-form-item>
        <a-form-item
          label="排序"
          name="sequence"
          :rules="[{ required: true, validator: checkSequence }]"
        >
          <a-input v-model:value="form.sequence" size="small" type="number" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { deptColumns as columns } from '@/config/columns'
import { message, Modal } from 'ant-design-vue'
import { createOrUpdateDepartmentApi, getDeptListApi, setDepartmentStatusApi } from '@/api/user'
import { createUuid } from '@/utils/encryp'
import useUserStore from '@/stores/user'

const userStore = useUserStore()
const formRef = ref()
const dataSource = ref([])
const total = ref(0)
const queryParams = reactive({
  status: '正常',
  departmentName: '',
  page: 1,
  pageSize: 20
})
const form = reactive({})
const visible = ref(false)
const title = ref('新增')

const checkSequence = (_rule, value) => {
  if (value * 1 > 0) {
    return Promise.resolve()
  } else {
    return Promise.reject('请输入大于0的数字')
  }
}
const checkCompanyAbbreviation = (_rule, value) => {
  if (value === '') {
    return Promise.reject('请输入公司英文简称')
  } else {
    // 校验强密码 ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$
    const objRegExp = /^[a-zA-Z]{3,20}$/
    if (objRegExp.test(value)) {
      return Promise.resolve()
    } else {
      return Promise.reject('请输入公司英文简称')
    }
  }
}

const handleChangeStatus = (row) => {
  if (row.id === userStore.userInfo.departmentID) {
    message.error('不能禁用自己所在的部门')
    return
  }
  if (row.departmentName === '管理员组' || row.departmentName === '总公司') {
    message.error(`不能修改管理员组${row.departmentName}`)
    return
  }
  Modal.confirm({
    title: '提示',
    content: `确认${row.status === '正常' ? '禁用' : '恢复'}部门吗?`,
    onOk: () => {
      setDepartmentStatusApi({
        DepartmentID: row.id,
        status: row.status === '正常' ? '禁用' : '正常'
      }).then(() => {
        // message.success('操作成功')
        getList()
        // row.status = row.status === '正常' ? '禁用' : '正常'
      })
    }
  })
}
const getList = () => {
  getDeptListApi(queryParams).then((res) => {
    total.value = res.totleCount
    dataSource.value = res.items
  })
}
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

const handleCreate = () => {
  visible.value = true
  title.value = '新增'
  form.name = ''
  form.id = ''
  form.simName = ''
  form.sequence = ''
}
const handleEdit = (row) => {
  visible.value = true
  title.value = '编辑'
  form.name = row.departmentName
  form.simName = row.simName
  form.sequence = row.sequence * 1 || ''
  form.id = row.id
}

const handleOk = () => {
  formRef.value
    .validateFields()
    .then((e) => {
      let params = {
        DepartmentName: form.name,
        SimName: form.simName,
        Sequence: form.sequence * 1,
        Status: '正常'
      }
      if (title.value === '新增') {
        params.Id = createUuid()
      } else {
        params.Id = form.id
      }
      createOrUpdateDepartmentApi(params).then(() => {
        message.success('操作成功')
        getList()
        visible.value = false
      })
    })
    .catch((e) => {
      console.log(e)
    })
}

onMounted(() => {
  handleSearch()
})
</script>

<style lang="less" scoped></style>
